package com.paw.core.intercepter;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.paw.common.constant.CommonConstant;
import com.paw.common.context.UserContext;
import com.paw.common.context.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Rubble
 * @date 2021/8/27
 **/
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    String userInfoEncode = request.getHeader(CommonConstant.USER_INFO);
    if(StrUtil.isNotEmpty(userInfoEncode) && isBase64(userInfoEncode)){
      try {
        String userInfoStr = Base64.decodeStr(userInfoEncode);
        UserContext userContext = JSON.parseObject(userInfoStr, UserContext.class);
        UserContextHolder.setUser(userContext);
      }catch (Exception e){
        log.error("userInfoStr interceptor ex {}",e.getMessage());
      }
    }

    return true;
  }


  @Override
  public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    UserContextHolder.remove();
  }

  private static boolean isBase64(String str) {
    String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
    return Pattern.matches(base64Pattern, str);
  }

}
